package com.huawei.apig.sdk.scheduling;

import com.huawei.apig.sdk.entity.ApiResponse;
import com.huawei.apig.sdk.entity.Message;
import com.huawei.apig.sdk.util.JDBCUtils;
import com.huawei.apig.sdk.util.SendSms;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 刘欣
 * @createTime 2023/8/24 10:22
 * @description
 */
@Component
@EnableScheduling
@Slf4j
public class SendMessages {


    @Scheduled(cron = "0/15 * * * * *")
    public void send() throws Exception {
        SendSms sendSms = new SendSms();
        //获取数据源
        List<Message> messageDb = getMessageDb();
        for (Message message : messageDb) {
            ApiResponse apiResponse = sendSms.send(message);
            //短信发送成功更新kk数据库中的状态
            if ("Success".equals(apiResponse.getDescription())) {
                Boolean tag = updateState(message);
                if (tag) {
                    log.info("更新为已发送状态");
                } else {
                    log.info("更新状态失败");
                }
            } else {
                log.info("短信验证码获取失败");
            }
        }
    }


    /**
     * 获取DB中数据
     *
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public List<Message> getMessageDb() throws SQLException, ClassNotFoundException {
        JDBCUtils jdbcUtils = new JDBCUtils();
        log.info("查询数据库中组织人员");
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<Message> messages = new ArrayList<>();


        log.info("建立数据连接");
        conn = jdbcUtils.getConnection();
        stmt = conn.createStatement();
        stmt.execute("USE kk_db");
        log.info("执行SQL语句SELECT * FROM kk_sms_send  WHERE state=0");
        String sql = "SELECT * FROM kk_sms_send where state  = 0";
        rs = stmt.executeQuery(sql);

        while (rs.next()) {
            Message message = new Message();
            //获取id
            String id = rs.getString("id");
            message.setId(Integer.parseInt(id));
            //解析验证码
            String messagetemp = rs.getString("content");
            String[] split_parts = messagetemp.split(" ");
            String[] split = split_parts[1].split("，");
            message.setContent(split[0].replace("#", ""));
            //获取电话号码
            String recive_phone = rs.getString("recive_phone");
            message.setRecive_phone(recive_phone);
            //获取状态
            String state = rs.getString("state");
            message.setState(Short.parseShort(state));
            messages.add(message);
        }


        JDBCUtils.close(conn, stmt, rs);

        log.info("查询结束");
        return messages;
    }

    public Boolean updateState(Message message) throws SQLException, ClassNotFoundException {
        JDBCUtils jdbcUtils = new JDBCUtils();
        log.info("更新数据库中短信状态");
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        log.info("建立数据连接");
        conn = jdbcUtils.getConnection();
        stmt = conn.createStatement();
        stmt.execute("USE kk_db");
        String query = "UPDATE kk_sms_send SET state  = ? WHERE id = ?";
        try {
            PreparedStatement statement = conn.prepareStatement(query);
            statement.setInt(1, 2);
            statement.setInt(2, message.getId());
            int i = statement.executeUpdate();
            if (i > 0) {
                log.info("短信状态更新成功");
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        log.info("短信状态更新失败");
        return false;
    }


}
